package com.blues.marker.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import org.hibernate.Session;    
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;    
import org.hibernate.Query;    
import org.hibernate.Session;
import org.hibernate.Transaction;    

import com.blues.marker.model.TableColumn;

@Controller
@RequestMapping("/account")
public class AccountController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView findAllAccounts() throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("account");
        mav.addObject("dataList", "Listing all accounts!");
        
		Configuration cfg = new Configuration();    
        cfg.configure();    
        SessionFactory sessionFactory=cfg.buildSessionFactory();
		
		Session s = null;    
        Transaction tx = null;    
        try {    
            s = sessionFactory.openSession();    
            tx = s.beginTransaction();    
            Query query = s.createQuery("from sys_user");
			mav.addObject("dataList", query.list());
            tx.commit();
			//mav.addObject("someText", s.get(TableColumn.class, "Test").toString());
			//System.out.println(s.get(TableColumn.class, "Test"));
        }catch(Exception e){    
            if(tx!=null){    
                tx.rollback();    
            }    
            e.printStackTrace();    
        }finally{    
            if(s!=null){    
                s.close();    
            }       
        }    
		
		return mav;
    }
    
    @RequestMapping(value="/{accountId}", method = RequestMethod.GET)
    public ModelAndView findAccount(@PathVariable int accountId, Model model) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("account");
        mav.addObject("someText", String.format("Showing account %d", accountId));
		
		return mav;
    }   
}